<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物料列表</title>
    <link rel="stylesheet" href="../../../css/style.css">
    <!--    &lt;!&ndash; 引入JQuery JS 文件 &ndash;&gt;-->
    <!--    <script src="../../../assets/js/jquery-3.7.1.min.js"></script>-->
    <!--    &lt;!&ndash; 引入 Bootstrap CSS 文件 &ndash;&gt;-->
    <!--    <link rel="stylesheet" href="../../../assets/css/bootstrap.min.css">-->
    <!--    &lt;!&ndash; 引入 Bootstrap JS 文件 &ndash;&gt;-->
    <!--    <script src="../../../assets/js/bootstrap.bundle.min.js"></script>-->

    <!-- 引入 jQuery-->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        /* 复制material_list.html的样式 */
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .table th {
            background-color: #f8f9fa;
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        .search-area {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
            width: 100%;
        }

        .search-row {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .search-item {
            flex: 0 0 auto;
            margin-right: 10px;
            margin-bottom: 5px;
        }

        .search-item .form-control, .search-item .form-select {
            width: 120px;
            height: 31px;
            font-size: 14px;
        }

        .search-item .btn {
            padding: 4px 8px;
        }

        .search-label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #555;
            white-space: nowrap;
        }

        .table-responsive {
            overflow-x: auto;
            margin: 0 -20px;
            padding: 0 20px;
        }

        .custom-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }

        .custom-table th {
            background: #f8f9fa;
            color: #495057;
            font-weight: 600;
            padding: 12px 15px;
            border-bottom: 2px solid #dee2e6;
            white-space: nowrap;
        }

        .custom-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            vertical-align: middle;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-buttons .btn {
            padding: 4px 10px;
            font-size: 13px;
            min-width: 60px;
            white-space: nowrap;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .page-title-icon {
            font-size: 24px;
        }

        .ms-auto {
            margin-left: auto;
        }

        .add-button {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 500;
        }

        .content-wrapper {
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin: 20px;
        }

        /* 表单验证样式 */
        .invalid-feedback {
            display: block;
            width: 100%;
            margin-top: 0.25rem;
            font-size: 0.875em;
            color: #dc3545;
        }

        .form-control.is-invalid, .form-select.is-invalid {
            border-color: #dc3545;
            padding-right: calc(1.5em + 0.75rem);
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(0.375em + 0.1875rem) center;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }

        .form-select.is-invalid {
            background-position: right 0.75rem center, center right 2.25rem;
            background-size: 16px 12px, calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }

        .form-control.is-invalid:focus, .form-select.is-invalid:focus {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
        }

        /* iOS风格模态框样式 */
        .ios-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1050;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .ios-modal.show {
            display: flex;
            opacity: 1;
        }

        .modal.ios-style .modal-dialog {
            max-width: 500px;
            margin: 0 auto;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 500px;
        }

        .modal.ios-style .modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            border: none;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            overflow: hidden;
        }

        .modal.ios-style .modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            position: relative;
        }

        .modal.ios-style .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            width: 100%;
            text-align: center;
        }

        .modal.ios-style .btn-close {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            opacity: 0.5;
            transition: opacity 0.2s;
        }

        .modal.ios-style .btn-close:hover {
            opacity: 1;
        }

        .modal.ios-style .modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .modal.ios-style .form-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
            margin-bottom: 8px;
        }

        .modal.ios-style .form-control,
        .modal.ios-style .form-select {
            border-radius: 12px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            padding: 10px 15px;
            font-size: 15px;
            transition: all 0.2s;
        }

        .modal.ios-style .form-control:focus,
        .modal.ios-style .form-select:focus {
            border-color: #007AFF;
            box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
        }

        .modal.ios-style .modal-footer {
            padding: 15px 20px 20px;
            border-top: 1px solid rgba(0, 0, 0, 0.1);
            justify-content: center;
            gap: 10px;
        }

        .modal.ios-style .btn {
            border-radius: 12px;
            padding: 10px 25px;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .modal.ios-style .btn-primary {
            background: #007AFF;
            border: none;
        }

        .modal.ios-style .btn-primary:hover {
            background: #0056CC;
        }

        .modal.ios-style .btn-secondary {
            background: #E5E5EA;
            border: none;
            color: #333;
        }

        .modal.ios-style .btn-secondary:hover {
            background: #D1D1D6;
        }

        /* 滚动条样式 */
        .modal.ios-style .modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .modal.ios-style .modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .modal.ios-style .modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }


        .ios-modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 0;
            max-width: 400px;
            width: 90%;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }

        .ios-modal.show .ios-modal-content {
            transform: scale(1);
        }

        .ios-modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .ios-modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .ios-modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .ios-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .ios-detail-item:last-child {
            border-bottom: none;
        }

        .ios-detail-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
        }

        .ios-detail-value {
            font-weight: 400;
            color: #333;
            font-size: 14px;
            text-align: right;
            max-width: 60%;
            word-wrap: break-word;
        }

        .ios-modal-footer {
            padding: 15px 20px 20px;
            text-align: center;
        }

        .ios-close-btn {
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .ios-close-btn:hover {
            background: #0056CC;
        }

        .modal.ios-style .btn-secondary {
            background: #E5E5EA;
            border: none;
            color: #333;
        }

        .modal.ios-style .btn-secondary:hover {
            background: #D1D1D6;
        }

        /* 滚动条样式 */
        .ios-modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .ios-modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .ios-modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }


        /* 表单验证样式 */
        .invalid-feedback {
            display: block;
            width: 100%;
            margin-top: 0.25rem;
            font-size: 0.875em;
            color: #dc3545;
        }

        .form-control.is-invalid, .form-select.is-invalid {
            border-color: #dc3545;
            padding-right: calc(1.5em + 0.75rem);
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(0.375em + 0.1875rem) center;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }

        .form-select.is-invalid {
            background-position: right 0.75rem center, center right 2.25rem;
            background-size: 16px 12px, calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }

        .form-control.is-invalid:focus, .form-select.is-invalid:focus {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
        }

        /* 添加按钮组样式 */
        .action-button-group {
            display: flex;
            gap: 15px;
            align-items: center;
            justify-content: flex-end;
        }

        .action-button-group .add-button {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            min-width: 140px;
            justify-content: center;
        }

        /* 调整模态框宽度 */
        .modal-xl-custom {
            max-width: 95%;
            width: 1400px;
        }

        .modal-lg-custom {
            max-width: 90%;
            width: 800px;
        }

        /* 调整表格单元格样式 */
        .records-table td {
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .records-table td.description-cell {
            white-space: normal;
            line-height: 1.4;
            min-width: 250px;
        }

        /* 添加可点击行的样式 */
        .records-table tbody tr {
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .records-table tbody tr:hover {
            background-color: rgba(0, 123, 255, 0.05);
        }

        /* 详情模态框中的信息项样式 */
        .detail-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .detail-item:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: 600;
            color: #666;
            margin-bottom: 5px;
        }

        .detail-value {
            color: #333;
            line-height: 1.5;
        }

        /* 调整详情模态框中的信息布局 */
        .detail-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .detail-grid .detail-item.full-width {
            grid-column: 1 / -1;
        }

        .detail-value.description {
            white-space: pre-wrap;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">员工</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="../homepage/employee_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html" class="active">物料列表</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_plan_list.html">查看生产计划</a></li>
                    <li><a href="../product/product_plan_commit.html">提交完成情况</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu active">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>
    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <div class="page-title">
                <span class="page-title-icon">📦</span>
                <span>物料列表</span>
                <div class="ms-auto">
                    <button class="btn btn-success add-button" onclick="addMaterial()">
                        <i class="fas fa-plus"></i> 申请新物料
                    </button>
                </div>
            </div>
            <!-- 搜索区域 -->
            <div class="search-area">
                <div class="search-row">
                    <div class="search-item">
                        <label class="search-label">物料编号</label>
                        <input type="text" class="form-control form-control-sm" id="searchCode"
                               placeholder="请输入编号">
                    </div>
                    <div class="search-item">
                        <label class="search-label">物料名称</label>
                        <input type="text" class="form-control form-control-sm" id="searchName"
                               placeholder="请输入名称">
                    </div>
                    <div class="search-item">
                        <label class="search-label">材料类型</label>
                        <select class="form-select form-select-sm" id="searchType">
                            <option value="">全部</option>
                            <option value="金属">金属</option>
                            <option value="合金">合金</option>
                            <option value="复合材料">复合材料</option>
                            <option value="其它">其它</option>
                        </select>
                    </div>
                    <div class="search-item">
                        <label class="search-label">供应商</label>
                        <input type="text" class="form-control form-control-sm" id="searchProvider"
                               placeholder="请输入供应商">
                    </div>
                    <div class="search-item">
                        <button class="btn btn-sm btn-outline-primary" onclick="searchMaterials()">🔍</button>
                    </div>
                    <div class="search-item">
                        <button class="btn btn-sm btn-outline-secondary" onclick="resetSearch()">↺</button>
                    </div>
                </div>
            </div>
            <!-- 数据表格 -->
            <div class="table-responsive">
                <table class="table table-hover table-striped custom-table mb-0">
                    <thead>
                    <tr>
                        <th>物料编号</th>
                        <th>物料名称</th>
                        <th>材料类型</th>
                        <th>供应商</th>
                        <th>厂址</th>
                        <th>入库时间</th>
                        <th>规格</th>
                        <th>联系人</th>
                        <th>手机</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="materialTableBody">
                    <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>
<!-- iOS风格物料详情模态框 -->
<div class="ios-modal" id="materialDetailModal">
    <div class="ios-modal-content">
        <div class="ios-modal-header">
            <h5 class="ios-modal-title">物料详情</h5>
        </div>
        <div class="ios-modal-body">
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料编号</span>
                <span class="ios-detail-value" id="detailMaterialNumber">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料名称</span>
                <span class="ios-detail-value" id="detailMaterialName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">材料类型</span>
                <span class="ios-detail-value" id="detailMaterialType">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">供应商</span>
                <span class="ios-detail-value" id="detailProviderName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">厂址</span>
                <span class="ios-detail-value" id="detailProviderAddress">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">入库时间</span>
                <span class="ios-detail-value" id="detailEntryDate">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">规格</span>
                <span class="ios-detail-value" id="detailSpecification">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">联系人</span>
                <span class="ios-detail-value" id="detailContact">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">手机</span>
                <span class="ios-detail-value" id="detailPhone">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料说明</span>
                <span class="ios-detail-value" id="detailDescription">-</span>
            </div>
        </div>
        <div class="ios-modal-footer">
            <button class="ios-close-btn" onclick="closeMaterialDetailModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 采购申请模态框 -->
<div class="modal ios-style fade" id="purchaseModal" tabindex="-1" aria-labelledby="purchaseModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-lg-custom">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="purchaseModalLabel">物料采购申请</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="purchaseForm">
                    <input type="hidden" id="purchaseMaterialId" name="materialId">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="purchaseMaterialName" class="form-label">物料名称 <span
                                    class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="purchaseMaterialName" name="materialName"
                                   readonly>
                        </div>
                        <div class="col-md-6">
                            <label for="purchaseMaterialType" class="form-label">材料类型 <span
                                    class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="purchaseMaterialType" name="materialType"
                                   readonly>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="purchaseQuantity" class="form-label">申请数量 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="purchaseQuantity" name="purchaseQuantity"
                                   required min="1">
                        </div>
                        <div class="col-md-6">
                            <label for="purchaseSpecification" class="form-label">规格 <span
                                    class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="purchaseSpecification" name="specification"
                                   readonly>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="purchaseProviderName" class="form-label">供应商 <span
                                    class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="purchaseProviderName" name="providerName"
                                   readonly>
                        </div>
                        <div class="col-md-6">
                            <label for="purchaseStorageDate" class="form-label">预计入库日期 <span
                                    class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="purchaseStorageDate" name="storageDate"
                                   required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="purchaseApplicantJobNumber" class="form-label">申请人工号 <span
                                    class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="purchaseApplicantJobNumber"
                                   name="applicantJobNumber" required>
                        </div>
                        <div class="col-md-6">
                            <label for="purchaseDesc" class="form-label">采购用途 <span
                                    class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="purchaseDesc" name="purchaseDesc" required>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitPurchaseRequest()">提交申请</button>
            </div>
        </div>
    </div>
</div>

<script src="../../assets/js/bootstrap.bundle.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        var menuItems = document.querySelectorAll('.menu-item > a');
        menuItems.forEach(function (item) {
            item.addEventListener('click', function (e) {
                var parent = item.parentElement;
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');
                e.preventDefault();
            });
        });
        // 添加首页链接的点击事件
        document.querySelector('.menu-item:first-child > a').addEventListener('click', function (e) {
            e.preventDefault(); // 阻止默认行为
            window.location.href = '../homepage/employee_home.html'; // 跳转到管理员首页
        });
        // 默认展开物料管理菜单
        const materialMenuItem = document.querySelector('.menu-item:nth-child(2)');
        if (materialMenuItem) {
            materialMenuItem.classList.add('active');
        }
        // 设置当前页面对应的菜单项为选中状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href') === filename) {
                link.classList.add('active');
            }
        });
        // 加载物料数据
        loadMaterials();
    });

    async function loadMaterials() {
        try {
            const response = await fetch('http://localhost:8080/api/materials');
            const data = await response.json();
            displayMaterials(data);
        } catch (error) {
            console.error('加载物料数据失败:', error);
        }
    }

    function searchMaterials() {
        const searchParams = {
            code: document.getElementById('searchCode').value.toLowerCase(),
            name: document.getElementById('searchName').value.toLowerCase(),
            type: document.getElementById('searchType').value,
            providerName: document.getElementById('searchProvider').value.toLowerCase()
        };
        const tbody = document.getElementById('materialTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            const cells = row.getElementsByTagName('td');
            const rowData = {
                code: cells[0].textContent.toLowerCase(),
                name: cells[1].textContent.toLowerCase(),
                type: cells[2].textContent,
                providerName: cells[3].textContent.toLowerCase()
            };
            let visible = true;
            for (const [key, value] of Object.entries(searchParams)) {
                if (value && !rowData[key].includes(value)) {
                    visible = false;
                    break;
                }
            }
            row.style.display = visible ? '' : 'none';
        }
    }

    function resetSearch() {
        document.getElementById('searchCode').value = '';
        document.getElementById('searchName').value = '';
        document.getElementById('searchType').value = '';
        document.getElementById('searchProvider').value = '';
        const tbody = document.getElementById('materialTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            row.style.display = '';
        }
    }

    function displayMaterials(materials) {
        const tbody = document.getElementById('materialTableBody');
        tbody.innerHTML = '';
        materials.forEach(material => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${material.materialNumber}</td>
                    <td>${material.name}</td>
                    <td>${material.type}</td>
                    <td>${material.providerName}</td>
                    <td>${material.providerAddress}</td>
                    <td>${material.entryDate || ''}</td>
                    <td>${material.specification}</td>
                    <td>${material.contact}</td>
                    <td>${material.phone}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-secondary" onclick="viewMaterialDetail(${material.id})">详情</button>
                            <button class="btn btn-sm btn-primary" onclick="requestPurchase(${material.id})">采购申请</button>
                        </div>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }

    // 查看物料详情 - iOS风格模态框
    function viewMaterialDetail(id) {
        getMaterialById(id).then(material => {
            if (material) {
                document.getElementById('detailMaterialNumber').textContent = material.materialNumber || '-';
                document.getElementById('detailMaterialName').textContent = material.name || '-';
                document.getElementById('detailMaterialType').textContent = material.type || '-';
                document.getElementById('detailProviderName').textContent = material.providerName || '-';
                document.getElementById('detailProviderAddress').textContent = material.providerAddress || '-';
                document.getElementById('detailEntryDate').textContent = material.entryDate || '-';
                document.getElementById('detailSpecification').textContent = material.specification || '-';
                document.getElementById('detailContact').textContent = material.contact || '-';
                document.getElementById('detailPhone').textContent = material.phone || '-';
                document.getElementById('detailDescription').textContent = material.description || '-';
                showMaterialDetailModal();
            }
        });
    }

    // 显示iOS风格模态框
    function showMaterialDetailModal() {
        const modal = document.getElementById('materialDetailModal');
        modal.classList.add('show');
        modal.onclick = function (e) {
            if (e.target === modal) {
                closeMaterialDetailModal();
            }
        };
    }

    // 关闭iOS风格模态框
    function closeMaterialDetailModal() {
        const modal = document.getElementById('materialDetailModal');
        modal.classList.remove('show');
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            closeMaterialDetailModal();
        }
    });

    async function getMaterialById(id) {
        try {
            const response = await fetch(`http://localhost:8080/api/materials/${id}`);
            const material = await response.json();
            return material;
        } catch (error) {
            console.error('获取物料详情失败:', error);
            return null;
        }
    }

    function requestPurchase(id) {
        getMaterialById(id).then(material => {
            if (material) {
                // 填充采购申请表单
                document.getElementById('purchaseMaterialId').value = material.id;
                document.getElementById('purchaseMaterialName').value = material.name || '';
                document.getElementById('purchaseMaterialType').value = material.type || '';
                document.getElementById('purchaseSpecification').value = material.specification || '';
                document.getElementById('purchaseProviderName').value = material.providerName || '';

                // 设置只读属性
                document.getElementById('purchaseMaterialName').setAttribute('readonly', 'readonly');
                document.getElementById('purchaseMaterialType').setAttribute('readonly', 'readonly');
                document.getElementById('purchaseSpecification').setAttribute('readonly', 'readonly');
                document.getElementById('purchaseProviderName').setAttribute('readonly', 'readonly');

                // 设置当前日期为默认入库日期
                const today = new Date();
                const formattedDate = today.toISOString().split('T')[0];
                document.getElementById('purchaseStorageDate').value = formattedDate;

                // 修改模态框标题
                document.getElementById('purchaseModalLabel').textContent = '物料采购申请';
                
                // 修改提交按钮文本
                document.querySelector('#purchaseModal .modal-footer .btn-primary').textContent = '提交申请';

                // 显示采购申请模态框
                const purchaseModal = new bootstrap.Modal(document.getElementById('purchaseModal'));
                purchaseModal.show();
            }
        });
    }

    // 修改提交采购申请函数
    async function submitPurchaseRequest() {
        // 表单验证
        const form = document.getElementById('purchaseForm');
        const requiredFields = [
            'purchaseMaterialName',
            'purchaseMaterialType',
            'purchaseQuantity',
            'purchaseSpecification',
            'purchaseProviderName',
            'purchaseStorageDate',
            'purchaseApplicantJobNumber',
            'purchaseDesc'
        ];
        let isValid = true;

        requiredFields.forEach(field => {
            const input = document.getElementById(field);
            if (!input.value.trim()) {
                input.classList.add('is-invalid');
                isValid = false;
            } else {
                input.classList.remove('is-invalid');
            }
        });

        if (!isValid) {
            alert('请填写所有必填字段');
            return;
        }

        // 数量验证
        const quantity = document.getElementById('purchaseQuantity').value;
        if (quantity < 1) {
            alert('申请数量必须大于0');
            return;
        }

        // 构建申请数据
        const purchaseData = {
            materialName: document.getElementById('purchaseMaterialName').value,
            materialType: document.getElementById('purchaseMaterialType').value,
            purchaseQuantity: parseInt(document.getElementById('purchaseQuantity').value),
            specification: document.getElementById('purchaseSpecification').value,
            providerName: document.getElementById('purchaseProviderName').value,
            storageDate: document.getElementById('purchaseStorageDate').value,
            applicantJobNumber: document.getElementById('purchaseApplicantJobNumber').value,
            purchaseDesc: document.getElementById('purchaseDesc').value,
            isApproved: false,
            approvalStatus: false
        };

        try {
            // 调用API提交申请
            const response = await fetch('http://localhost:8080/api/material-purchase/new', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(purchaseData)
            });

            if (!response.ok) {
                throw new Error('提交申请失败');
            }

            // 关闭模态框
            const purchaseModal = bootstrap.Modal.getInstance(document.getElementById('purchaseModal'));
            purchaseModal.hide();

            // 重置表单
            form.reset();

            // 恢复只读属性
            document.getElementById('purchaseMaterialName').setAttribute('readonly', 'readonly');
            document.getElementById('purchaseMaterialType').setAttribute('readonly', 'readonly');
            document.getElementById('purchaseSpecification').setAttribute('readonly', 'readonly');
            document.getElementById('purchaseProviderName').setAttribute('readonly', 'readonly');

            alert('新物料申请提交成功');

        } catch (error) {
            console.error('提交申请失败:', error);
            alert('提交申请失败，请重试');
        }
    }

    // 申请新物料
    function addMaterial() {
        // 清空表单
        document.getElementById('purchaseForm').reset();
        
        // 移除只读属性
        document.getElementById('purchaseMaterialName').removeAttribute('readonly');
        document.getElementById('purchaseMaterialType').removeAttribute('readonly');
        document.getElementById('purchaseSpecification').removeAttribute('readonly');
        document.getElementById('purchaseProviderName').removeAttribute('readonly');
        
        // 修改模态框标题
        document.getElementById('purchaseModalLabel').textContent = '新物料申请';
        
        // 修改提交按钮文本
        document.querySelector('#purchaseModal .modal-footer .btn-primary').textContent = '提交申请';
        
        // 显示模态框
        const purchaseModal = new bootstrap.Modal(document.getElementById('purchaseModal'));
        purchaseModal.show();
    }

    function logout() {
        localStorage.removeItem('userInfo');
        window.location.href = '../../../login.html';
    }
</script>
</body>
</html>